/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-07-24
*/
package com.rzico.order.service;

import com.alibaba.fastjson.JSON;
import com.rzico.account.entity.Payment;
import com.rzico.account.entity.Receivable;
import com.rzico.account.enumx.OrderTypeEnum;
import com.rzico.account.model.Attach;
import com.rzico.account.service.PaymentService;
import com.rzico.account.service.ReceivableService;
import com.rzico.base.BaseMapper;
import com.rzico.base.impl.BaseServiceImpl;
import com.rzico.basics.entity.Bom;
import com.rzico.basics.entity.BomItem;
import com.rzico.basics.entity.Member;
import com.rzico.basics.entity.Product;
import com.rzico.basics.service.BomItemService;
import com.rzico.basics.service.BomService;
import com.rzico.basics.service.ProductService;
import com.rzico.exception.CustomException;
import com.rzico.order.entity.*;
import com.rzico.order.mapper.VirtualStockMapper;
import com.rzico.util.RedisHandler;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import com.rzico.order.mapper.VirtualProductMapper;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * <pre>
 * 虚拟商品业务类
 * </pre>
 *
 * @author Rzico Boot
 * @version 1.0
 */
@Service
public class VirtualProductService extends BaseServiceImpl<VirtualProduct, String> {

    @Autowired
    private VirtualProductMapper virtualProductMapper;

    @Autowired
    private VirtualStockMapper virtualStockMapper;

    @Autowired
    private ProductService productService;

    @Autowired
    private WarehouseService warehouseService;

    @Autowired
    private ReceivableService receivableService;

    @Autowired
    private BomService bomService;

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private BomItemService bomItemService;

    @Autowired
    private RedisHandler redisHandler;

    @Override
    public BaseMapper<VirtualProduct, String> getMapper() {
        return virtualProductMapper;
    }

    @Transactional(rollbackFor = Exception.class)
    private VirtualStock addProduct(Product product,Long memberId,Long orderId) {

        String key = "virtual-stock-"+String.valueOf(product.getEnterpriseId()).concat("-").concat(String.valueOf(product.getId())).concat("-").concat(String.valueOf(memberId));
        String value = key;
        while (!redisHandler.lock(key,value)) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        try {
            VirtualStock virtualStock = new VirtualStock();
            virtualStock.setProductId(product.getId());
            virtualStock.setEnterpriseId(product.getEnterpriseId());
            virtualStock.setMemberId(memberId);
            if (orderId!=null) {
                virtualStock.setOrderId(orderId);
            }
            List<VirtualStock> virtualStockList = virtualStockMapper.select(virtualStock);
            if (virtualStockList.size() > 0) {
                virtualStock = virtualStockList.get(0);
            } else {
                virtualStock.setAllocatedStock(BigDecimal.ZERO);
                virtualStock.setCreateDate(new Date());
                virtualStock.setGoodsId(product.getGoodsId());
                virtualStock.setCost(BigDecimal.ZERO);
                virtualStock.setStock(BigDecimal.ZERO);
                virtualStock.setPrice(BigDecimal.ZERO);
                virtualStock.setTotalInStock(BigDecimal.ZERO);
                virtualStock.setTotalOutStock(BigDecimal.ZERO);
                virtualStock.setOrderId(orderId);
                virtualStockMapper.insertUseGeneratedKeys(virtualStock);
            }
            return virtualStock;
        } finally {
            redisHandler.unlock(key,value);
        }

    }

    @Transactional(rollbackFor = Exception.class)
    public VirtualProduct addMember(Member member,Integer quantity,Long productId,String paymentPluginId,String sn) {

        Product product = productService.selectByPrimaryKey(productId);
        if (product.getSubType().equals(3)) {

            VirtualStock virtualStock = addProduct(product,member.getId(),null);
            Map<String,Object> params = new HashMap<>();
            params.put("id",virtualStock.getId());
            params.put("price",product.getPrice().multiply(new BigDecimal(quantity)));
            params.put("cost",product.getCost().multiply(new BigDecimal(quantity)));
            params.put("stock",quantity);
            virtualStockMapper.addStock(params);

            VirtualProduct virtualProduct = new VirtualProduct();
            virtualProduct.setVirtualStockId(virtualStock.getId());
            virtualProduct.setCost(product.getCost().multiply(new BigDecimal(quantity)));
            virtualProduct.setCreateDate(new Date());
            virtualProduct.setDiscount(BigDecimal.ZERO);
            virtualProduct.setQuantity(new BigDecimal(quantity));
            virtualProduct.setMemberId(member.getId());
            virtualProduct.setPrice(product.getPrice().multiply(new BigDecimal(quantity)));
            virtualProduct.setEnterpriseId(product.getEnterpriseId());
            virtualProduct.setOrderId(null);
            virtualProduct.setOrderSn(null);
            virtualProduct.setShippingId(null);
            virtualProduct.setName(product.getName());
            virtualProduct.setSpec(product.getSpec());
            virtualProduct.setThumbnail(product.getThumbnail());
            virtualProduct.setUnit(product.getUnit());
            virtualProduct.setVirtualType(1);
            virtualProduct.setSubType(product.getSubType());
            virtualProduct.setSn(product.getSn());
            virtualProduct.setProductId(product.getId());
            virtualProductMapper.insertUseGeneratedKeys(virtualProduct);

            //同时生成应付款
            Receivable receivable = new Receivable();
            receivable.setAmount(product.getPrice().multiply(new BigDecimal(quantity)));
            if ("debtPayPlugin".equals(paymentPluginId)) {
                receivable.setAmountPaid(BigDecimal.ZERO);
                receivable.setStatus(0);
            } else {
                receivable.setAmountPaid(receivable.getAmount());
                receivable.setStatus(2);
            }
            receivable.setQuantityPaid(0);
            receivable.setQuantity(0);
            receivable.setType(0);
            //订单未付款
            receivable.setPaymentPluginId("cashPayPlugin");
            receivable.setPaymentPluginName("现金");
            receivable.setDeleted(false);
            receivable.setMemberId(member.getId());
            receivable.setEnterpriseId(member.getEnterpriseId());
            receivableService.insertUseGeneratedKeys(receivable);
            if (!"debtPayPlugin".equals(paymentPluginId)) {
                Payment payment = new Payment();
                payment.setCreateDate(new Date());
                payment.setDeleted(false);
                payment.setSn(sn);
                payment.setAmount(receivable.getAmount());
                payment.setRefund(BigDecimal.ZERO);
                payment.setFee(BigDecimal.ZERO);
                payment.setAttach(null);
                payment.setEnterpriseId(receivable.getEnterpriseId());
                payment.setMemberId(receivable.getMemberId());
                payment.setExpire(DateUtils.addMinutes(new Date(), 30));
                payment.setStatus(Payment.STATUS_WAITING);
                payment.setType(Payment.TYPE_ORDER);
                payment.setMethod(Payment.METHOD_ONLINE);
                payment.setMemo("压桶-后台登记");
                payment.setWay(1);
                payment.setPaymentPluginId(paymentPluginId);
                if ("cashPayPlugin".equals(paymentPluginId)) {
                    payment.setPaymentPluginName("现金");
                } else
                if ("bankPayPlugin".equals(paymentPluginId)) {
                    payment.setPaymentPluginName("转账");
                } else {
                    throw new CustomException("不支持的付款方式");
                }
                payment.setOrderType(0);
                payment.setQuantity(BigDecimal.ZERO);
                payment.setAttach(null);
                paymentService.insertUseGeneratedKeys(payment);

            }

            return virtualProduct;

        } else {
            throw new CustomException("不是压桶商品");
        }


    }


    @Transactional(rollbackFor = Exception.class)
    public VirtualProduct decMember(Member member,Integer quantity,Long productId,String paymentPluginId,String sn) {

        Product product = productService.selectByPrimaryKey(productId);
        if (product.getSubType().equals(3)) {

            quantity = - quantity;

            VirtualStock virtualStock = addProduct(product,member.getId(),null);
            Map<String,Object> params = new HashMap<>();
            params.put("id",virtualStock.getId());
            params.put("price",product.getPrice().multiply(new BigDecimal(quantity)));
            params.put("cost",product.getCost().multiply(new BigDecimal(quantity)));
            params.put("stock",quantity);
            virtualStockMapper.addStock(params);

            virtualStock = virtualStockMapper.selectByPrimaryKey(virtualStock.getId());
            if (virtualStock.getStock().compareTo(BigDecimal.ZERO)<0) {
                throw new CustomException("压桶数不足");
            }

            VirtualProduct virtualProduct = new VirtualProduct();
            virtualProduct.setVirtualStockId(virtualStock.getId());
            virtualProduct.setCost(product.getCost().multiply(new BigDecimal(quantity)));
            virtualProduct.setCreateDate(new Date());
            virtualProduct.setDiscount(BigDecimal.ZERO);
            virtualProduct.setQuantity(new BigDecimal(quantity));
            virtualProduct.setMemberId(member.getId());
            virtualProduct.setPrice(product.getPrice().multiply(new BigDecimal(quantity)));
            virtualProduct.setEnterpriseId(product.getEnterpriseId());
            virtualProduct.setOrderId(null);
            virtualProduct.setOrderSn(null);
            virtualProduct.setShippingId(null);
            virtualProduct.setName(product.getName());
            virtualProduct.setSpec(product.getSpec());
            virtualProduct.setThumbnail(product.getThumbnail());
            virtualProduct.setUnit(product.getUnit());
            virtualProduct.setVirtualType(2);
            virtualProduct.setSubType(product.getSubType());
            virtualProduct.setSn(product.getSn());
            virtualProduct.setProductId(product.getId());
            virtualProductMapper.insertUseGeneratedKeys(virtualProduct);


            //同时生成应付款
            Receivable receivable = new Receivable();
            receivable.setAmount(product.getPrice().multiply(new BigDecimal(quantity)));
            if ("debtPayPlugin".equals(paymentPluginId)) {
                receivable.setAmountPaid(BigDecimal.ZERO);
                receivable.setStatus(0);
            } else {
                receivable.setAmountPaid(receivable.getAmount());
                receivable.setStatus(2);
            }
            receivable.setQuantityPaid(0);
            receivable.setQuantity(0);
            receivable.setType(0);
            //订单未付款
            receivable.setPaymentPluginId("cashPayPlugin");
            receivable.setPaymentPluginName("现金");
            receivable.setDeleted(false);
            receivable.setMemberId(member.getId());
            receivable.setEnterpriseId(member.getEnterpriseId());
            receivableService.insertUseGeneratedKeys(receivable);
            if (!"debtPayPlugin".equals(paymentPluginId)) {
                Payment payment = new Payment();
                payment.setCreateDate(new Date());
                payment.setDeleted(false);
                payment.setSn(sn);
                payment.setAmount(receivable.getAmount());
                payment.setRefund(BigDecimal.ZERO);
                payment.setFee(BigDecimal.ZERO);
                payment.setAttach(null);
                payment.setEnterpriseId(receivable.getEnterpriseId());
                payment.setMemberId(receivable.getMemberId());
                payment.setExpire(DateUtils.addMinutes(new Date(), 30));
                payment.setStatus(Payment.STATUS_WAITING);
                payment.setType(Payment.TYPE_ORDER);
                payment.setMethod(Payment.METHOD_ONLINE);
                payment.setMemo("退桶-后台登记");
                payment.setWay(1);
                payment.setPaymentPluginId(paymentPluginId);
                if ("cashPayPlugin".equals(paymentPluginId)) {
                    payment.setPaymentPluginName("现金");
                } else
                if ("bankPayPlugin".equals(paymentPluginId)) {
                    payment.setPaymentPluginName("转账");
                } else {
                    throw new CustomException("不支持的付款方式");
                }
                payment.setOrderType(0);
                payment.setQuantity(BigDecimal.ZERO);
                payment.setAttach(null);
                paymentService.insertUseGeneratedKeys(payment);

            }

            return virtualProduct;

        } else {
            throw new CustomException("不是压桶商品");
        }


    }

    @Transactional(rollbackFor = Exception.class)
    public VirtualProduct addShipping(Shipping shipping,Integer quantity,Long productId) {

            Product product = productService.selectByPrimaryKey(productId);
            if (product.getSubType().equals(3)) {

                VirtualStock virtualStock = addProduct(product,shipping.getMemberId(),null);
                Map<String,Object> params = new HashMap<>();
                params.put("id",virtualStock.getId());
                params.put("price",product.getPrice().multiply(new BigDecimal(quantity)));
                params.put("cost",product.getCost().multiply(new BigDecimal(quantity)));
                params.put("stock",quantity);
                virtualStockMapper.addStock(params);

                VirtualProduct virtualProduct = new VirtualProduct();
                virtualProduct.setVirtualStockId(virtualStock.getId());
                virtualProduct.setCost(product.getCost().multiply(new BigDecimal(quantity)));
                virtualProduct.setCreateDate(new Date());
                virtualProduct.setDiscount(BigDecimal.ZERO);
                virtualProduct.setQuantity(new BigDecimal(quantity));
                virtualProduct.setMemberId(shipping.getMemberId());
                virtualProduct.setPrice(product.getPrice().multiply(new BigDecimal(quantity)));
                virtualProduct.setEnterpriseId(product.getEnterpriseId());
                virtualProduct.setOrderId(null);
                virtualProduct.setOrderSn(null);
                virtualProduct.setShippingId(shipping.getId());
                virtualProduct.setName(product.getName());
                virtualProduct.setSpec(product.getSpec());
                virtualProduct.setThumbnail(product.getThumbnail());
                virtualProduct.setUnit(product.getUnit());
                virtualProduct.setVirtualType(1);
                virtualProduct.setSubType(product.getSubType());
                virtualProduct.setSn(product.getSn());
                virtualProduct.setProductId(product.getId());
                virtualProduct.setShopId(shipping.getShopId());
                virtualProduct.setShippingEmployeeId(shipping.getShippingEmployeeId());
                virtualProductMapper.insertUseGeneratedKeys(virtualProduct);

                //同时生成应付款
//                Receivable receivable = new Receivable();
//                receivable.setAmount(product.getPrice().multiply(new BigDecimal(quantity)));
//                receivable.setAmountPaid(BigDecimal.ZERO);
//                receivable.setQuantityPaid(0);
//                receivable.setQuantity(0);
//                receivable.setType(0);
//                //订单未付款
//                receivable.setStatus(0);
//                receivable.setPaymentPluginId("cashPayPlugin");
//                receivable.setPaymentPluginName("现金");
//                receivable.setDeleted(false);
//                receivable.setMemberId(shipping.getMemberId());
//                receivable.setEnterpriseId(shipping.getEnterpriseId());
//                if (shipping.getOrderId()!=null) {
//                    receivable.setOrderId(shipping.getOrderId());
//                    receivable.setOrderSn(shipping.getOrderSn());
//                    receivable.setOrderType(0);
//                } else {
//                    Warehouse warehouse = warehouseService.selectByPrimaryKey(shipping.getWarehouseId());
//                    receivable.setOrderId(shipping.getWarehouseId());
//                    receivable.setOrderSn(warehouse.getSn());
//                    receivable.setOrderType(1);
//                }
//                receivableService.insertUseGeneratedKeys(receivable);


                return virtualProduct;

            } else {
                throw new CustomException("不是压桶商品");
            }


    }


    @Transactional(rollbackFor = Exception.class)
    public VirtualProduct delShipping(Shipping shipping,Integer quantity,Long productId) {

        Product product = productService.selectByPrimaryKey(productId);
        if (product.getSubType().equals(3)) {

            quantity = - quantity;

            VirtualStock virtualStock = addProduct(product,shipping.getMemberId(),null);
            Map<String,Object> params = new HashMap<>();
            params.put("id",virtualStock.getId());
            params.put("price",product.getPrice().multiply(new BigDecimal(quantity)));
            params.put("cost",product.getCost().multiply(new BigDecimal(quantity)));
            params.put("stock",quantity);
            virtualStockMapper.addStock(params);

            virtualStock = virtualStockMapper.selectByPrimaryKey(virtualStock.getId());
            if (virtualStock.getStock().compareTo(BigDecimal.ZERO)<0) {
                throw new CustomException("压桶数不足");
            }

            VirtualProduct virtualProduct = new VirtualProduct();
            virtualProduct.setVirtualStockId(virtualStock.getId());
            virtualProduct.setCost(product.getCost().multiply(new BigDecimal(quantity)));
            virtualProduct.setCreateDate(new Date());
            virtualProduct.setDiscount(BigDecimal.ZERO);
            virtualProduct.setQuantity(new BigDecimal(quantity));
            virtualProduct.setMemberId(shipping.getMemberId());
            virtualProduct.setPrice(product.getPrice().multiply(new BigDecimal(quantity)));
            virtualProduct.setEnterpriseId(product.getEnterpriseId());
            virtualProduct.setOrderId(null);
            virtualProduct.setOrderSn(null);
            virtualProduct.setShippingId(shipping.getId());
            virtualProduct.setName(product.getName());
            virtualProduct.setSpec(product.getSpec());
            virtualProduct.setThumbnail(product.getThumbnail());
            virtualProduct.setUnit(product.getUnit());
            virtualProduct.setVirtualType(2);
            virtualProduct.setSubType(product.getSubType());
            virtualProduct.setSn(product.getSn());
            virtualProduct.setProductId(product.getId());
            virtualProduct.setShopId(shipping.getShopId());
            virtualProduct.setShippingEmployeeId(shipping.getShippingEmployeeId());
            virtualProductMapper.insertUseGeneratedKeys(virtualProduct);


            //同时生成应付款
//            Receivable receivable = new Receivable();
//            receivable.setAmount(product.getPrice().multiply(new BigDecimal(quantity)));
//            receivable.setAmountPaid(BigDecimal.ZERO);
//            receivable.setQuantityPaid(0);
//            receivable.setQuantity(0);
//            receivable.setType(1);
//            //订单未付款
//            receivable.setStatus(0);
//            receivable.setPaymentPluginId("cashPayPlugin");
//            receivable.setPaymentPluginName("现金");
//            receivable.setDeleted(false);
//            receivable.setMemberId(shipping.getMemberId());
//            receivable.setEnterpriseId(shipping.getEnterpriseId());
//            if (shipping.getOrderId()!=null) {
//                receivable.setOrderId(shipping.getOrderId());
//                receivable.setOrderSn(shipping.getOrderSn());
//                receivable.setOrderType(0);
//            } else {
//                Warehouse warehouse = warehouseService.selectByPrimaryKey(shipping.getWarehouseId());
//                receivable.setOrderId(shipping.getWarehouseId());
//                receivable.setOrderSn(warehouse.getSn());
//                receivable.setOrderType(1);
//            }
//            receivableService.insertUseGeneratedKeys(receivable);

            return virtualProduct;
        } else {
            throw new CustomException("不是压桶商品");
        }


    }
    @Transactional(rollbackFor = Exception.class)
    public void addOrder(Order order) {

        List<OrderItem> itemList = new ArrayList<>();

        //处理单次套餐里的水票
        for (OrderItem orderItem:order.getItemList()) {

            itemList.add(orderItem);
            if (orderItem.getSubType().equals(1)) {
                //套餐时，生成配送计划
                Bom bom = null;
                Map<String,Object> params = new HashMap<>();
                params.put("enterpriseId",order.getEnterpriseId());
                params.put("productId",orderItem.getProductId());
                List<Bom> bomList = bomService.selectList(params);
                if (bomList.size()>0) {
                    bom = bomList.get(0);
                }

                if (bom==null) {
                    throw new CustomException("请设置套餐");
                }

                if (bom.getQuantity()>1) {
                    continue;
                }

                List<BomItem> bomItemList = bomItemService.getItemList(bom.getId());
                for (BomItem bomItem:bomItemList) {
                    Product product = productService.selectByPrimaryKey(bomItem.getProductId());
                    OrderItem giftItem = new OrderItem();
                    giftItem.setThumbnail(product.getThumbnail());
                    giftItem.setName(product.getName());
                    giftItem.setUnit(product.getUnit());
                    giftItem.setSn(product.getSn());
                    giftItem.setSpec(product.getSpec());
                    giftItem.setCost(product.getCost());
                    giftItem.setDiscount(BigDecimal.ZERO);
                    giftItem.setIsGift(true);
                    if (bomItem.getConvRate()==null || bomItem.getConvRate().compareTo(BigDecimal.ZERO)==0) {
                        bomItem.setConvRate(BigDecimal.ONE);
                    }
                    giftItem.setQuantity(bomItem.getConvRate().multiply(orderItem.getQuantity()));
                    giftItem.setPrice(BigDecimal.ZERO);
                    giftItem.setShippedQuantity(BigDecimal.ZERO);
                    giftItem.setReturnQuantity(BigDecimal.ZERO);
                    giftItem.setProductId(bomItem.getProductId());
                    giftItem.setSubType(product.getSubType());
                    itemList.add(giftItem);
                }

            }
        }

        for (OrderItem orderItem:itemList) {
            Product product = productService.selectByPrimaryKey(orderItem.getProductId());
            if (!orderItem.getSubType().equals(0) && !orderItem.getSubType().equals(1)) {

                Long orderId = null;
                if (orderItem.getSubType().equals(3)) {
                    orderId = order.getId();
                }

                VirtualStock virtualStock = addProduct(product,order.getMemberId(),orderId);
                Map<String,Object> params = new HashMap<>();
                params.put("id",virtualStock.getId());
                params.put("price",orderItem.getPrice().multiply(orderItem.getQuantity()));
                params.put("cost",orderItem.getCost().multiply(orderItem.getQuantity()));
                params.put("stock",orderItem.getQuantity());
                virtualStockMapper.addStock(params);

                VirtualProduct virtualProduct = new VirtualProduct();
                virtualProduct.setVirtualStockId(virtualStock.getId());
                virtualProduct.setCost(orderItem.getCost());
                virtualProduct.setCreateDate(new Date());
                virtualProduct.setDiscount(orderItem.getDiscount());
                virtualProduct.setQuantity(orderItem.getQuantity());
                virtualProduct.setMemberId(order.getMemberId());
                virtualProduct.setPrice(orderItem.getPrice().multiply(orderItem.getQuantity()));
                virtualProduct.setEnterpriseId(product.getEnterpriseId());
                virtualProduct.setOrderId(order.getId());
                virtualProduct.setOrderSn(order.getSn());
                virtualProduct.setName(orderItem.getName());
                virtualProduct.setSpec(orderItem.getSpec());
                virtualProduct.setThumbnail(orderItem.getThumbnail());
                virtualProduct.setUnit(orderItem.getUnit());
                virtualProduct.setVirtualType(1);
                virtualProduct.setSubType(orderItem.getSubType());
                virtualProduct.setSn(orderItem.getSn());
                virtualProduct.setProductId(orderItem.getProductId());
                virtualProductMapper.insertUseGeneratedKeys(virtualProduct);

            }
        }

    }

    public boolean checkAskfor(Askfor askfor) {
        for (AskforItem askforItem:askfor.getItemList()) {
            Product product = productService.selectByPrimaryKey(askforItem.getProductId());
            if (!product.getSubType().equals(0) && !product.getSubType().equals(1)) {
                Long orderId = null;
                if (askforItem.getSubType().equals(3)) {
                    orderId = askfor.getOrderId();
                }
                VirtualStock virtualStock = addProduct(product,askfor.getMemberId(),orderId);
                if (virtualStock.getStock().compareTo(askforItem.getQuantity())<0) {
                    return false;
                }
            }
        }
        return true;
    }


    @Transactional(rollbackFor = Exception.class)
    public void addAskfor(Askfor askfor) {

        List<AskforItem> itemList = new ArrayList<>() ;

        //处理单次套餐里的水票
        for (AskforItem orderItem:askfor.getItemList()) {
            itemList.add(orderItem);
            if (orderItem.getSubType().equals(1)) {

                Bom bom = null;
                Map<String,Object> params = new HashMap<>();
                params.put("enterpriseId",askfor.getEnterpriseId());
                params.put("productId",orderItem.getProductId());
                List<Bom> bomList = bomService.selectList(params);
                if (bomList.size()>0) {
                    bom = bomList.get(0);
                }

                if (bom==null) {
                    throw new CustomException("请设置套餐");
                }

                if (bom.getQuantity()>1) {
                    continue;
                }

                List<BomItem> bomItemList = bomItemService.getItemList(bom.getId());
                for (BomItem bomItem:bomItemList) {
                    Product product = productService.selectByPrimaryKey(bomItem.getProductId());
                    AskforItem giftItem = new AskforItem();
                    giftItem.setThumbnail(product.getThumbnail());
                    giftItem.setName(product.getName());
                    giftItem.setUnit(product.getUnit());
                    giftItem.setSn(product.getSn());
                    giftItem.setSpec(product.getSpec());
                    giftItem.setCost(product.getCost());
                    giftItem.setDiscount(BigDecimal.ZERO);
                    giftItem.setIsGift(true);
                    if (bomItem.getConvRate()==null || bomItem.getConvRate().compareTo(BigDecimal.ZERO)==0) {
                        bomItem.setConvRate(BigDecimal.ONE);
                    }
                    giftItem.setQuantity(bomItem.getConvRate().multiply(orderItem.getQuantity()));
                    giftItem.setPrice(BigDecimal.ZERO);
                    giftItem.setProductId(bomItem.getProductId());
                    giftItem.setSubType(product.getSubType());
                    itemList.add(giftItem);
                }

            }
        }

        for (AskforItem askforItem:itemList) {
            Product product = productService.selectByPrimaryKey(askforItem.getProductId());
            if (!askforItem.getSubType().equals(0) && !askforItem.getSubType().equals(1)) {

                Long orderId = null;
                if (askforItem.getSubType().equals(3)) {
                    orderId = askfor.getOrderId();
                }
                VirtualStock virtualStock = addProduct(product,askfor.getMemberId(),orderId);

                if (virtualStock.getStock().compareTo(askforItem.getQuantity())<0) {
                    throw new CustomException("余票不足-".concat(askforItem.getName()));
                }

                Map<String,Object> params = new HashMap<>();
                params.put("id",virtualStock.getId());
                params.put("price",askforItem.getPrice().multiply(askforItem.getQuantity()));
                params.put("cost",askforItem.getCost().multiply(askforItem.getQuantity()));
                params.put("stock",askforItem.getQuantity());
                virtualStockMapper.decStock(params);

                virtualStock = virtualStockMapper.selectByPrimaryKey(virtualStock.getId());

                if (virtualStock.getStock().compareTo(BigDecimal.ZERO)<0) {
                    throw new CustomException("余票不足");
                }

                VirtualProduct virtualProduct = new VirtualProduct();
                virtualProduct.setVirtualStockId(virtualStock.getId());
                virtualProduct.setCost(askforItem.getCost());
                virtualProduct.setCreateDate(new Date());
                virtualProduct.setDiscount(askforItem.getDiscount());
                virtualProduct.setQuantity(BigDecimal.ZERO.subtract(askforItem.getQuantity()));
                virtualProduct.setMemberId(askfor.getMemberId());
                virtualProduct.setPrice(BigDecimal.ZERO.subtract(askforItem.getPrice().multiply(askforItem.getQuantity())));
                virtualProduct.setEnterpriseId(product.getEnterpriseId());
                virtualProduct.setOrderId(askfor.getOrderId());
                virtualProduct.setOrderSn(askfor.getOrderSn());
                virtualProduct.setName(askforItem.getName());
                virtualProduct.setSpec(askforItem.getSpec());
                virtualProduct.setThumbnail(askforItem.getThumbnail());
                virtualProduct.setUnit(askforItem.getUnit());
                virtualProduct.setVirtualType(2);
                virtualProduct.setSubType(askforItem.getSubType());
                virtualProduct.setSn(askforItem.getSn());
                virtualProduct.setProductId(askforItem.getProductId());
                virtualProductMapper.insertUseGeneratedKeys(virtualProduct);

            }
        }

    }
}
